package cn.org.mrliu.ssm.util.log4j;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties;

/**
 * <code>
 * 重写父类的createSession方法
 * 目的:启用ssl
 * 	 props.put("mail.smtp.starttls.enable", "true");
 *	 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
 * </code>
 * 
 * @author MrLiu
 *
 */
public class SMTPAppender extends org.apache.log4j.net.SMTPAppender {
	private boolean ssl = true;

	/**
	 * Create mail session.
	 * 
	 * @return mail session, may not be null.
	 * @since 1.2.14
	 */
	protected Session createSession() {
		Properties props = null;
		try {
			props = new Properties(System.getProperties());
		} catch (SecurityException ex) {
			props = new Properties();
		}

		String prefix = "mail.smtp";
		if (getSMTPProtocol() != null) {
			props.put("mail.transport.protocol", getSMTPProtocol());
			prefix = "mail." + getSMTPProtocol();
		}
		if (getSMTPHost() != null) {
			props.put(prefix + ".host", getSMTPHost());
		}
		if (getSMTPPort() > 0) {
			props.put(prefix + ".port", String.valueOf(getSMTPPort()));
		}

		Authenticator auth = null;
		if (getSMTPPassword() != null && getSMTPUsername() != null) {
			props.put(prefix + ".auth", "true");
			auth = new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(getSMTPUsername(), getSMTPPassword());
				}
			};
		}
		if (ssl) {
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}
		Session session = Session.getInstance(props, auth);
		if (getSMTPProtocol() != null) {
			session.setProtocolForAddress("rfc822", getSMTPProtocol());
		}
		if (getSMTPDebug()) {
			session.setDebug(getSMTPDebug());
		}
		return session;
	}

	public boolean isSsl() {
		return ssl;
	}

	public void setSsl(boolean ssl) {
		this.ssl = ssl;
	}
}
